package com.cs.tools.util;

import cn.hutool.crypto.digest.DigestUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JwtUtil {

   private final  static String key = DigestUtil.bcrypt("lucky");

   private static Jws<Claims> jws;




   /**
    * 创建token字符串
    * @param username
    * @param role
    * @return
    */
   public static String createToken(String username,String role,long expiredTime){
      return Jwts.builder().setHeaderParam("alg","SHA256")
              .setHeaderParam("type","JWT")
              .claim("username",username)
              .claim("role",role)
              .setExpiration(new Date(System.currentTimeMillis()+expiredTime))
              .signWith(SignatureAlgorithm.HS256,key.getBytes())
              .compact();

   }

   private  static void parseToken(String token){
      jws  = Jwts.parser().setSigningKey(key.getBytes())
              .parseClaimsJws(token);
   }

   /**
    * 取出claim中值
    * @param token
    * @param key
    * @return
    */
   public static String getClaim(String token,String key){
      parseToken(token);
      return (String) jws.getBody().get(key);
   }





}

